package com.zktravel.service.order;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.odianyun.util.BeanUtils;
import com.odianyun.util.date.DatetimeUtils;
import com.zktravel.constants.CommonConstant;
import com.zktravel.core.exception.VisibleException;
import com.zktravel.enums.CodeEnum;
import com.zktravel.mapper.CusCouponMapper;
import com.zktravel.mapper.TaProductMapper;
import com.zktravel.model.dto.coupon.CouListResponse;
import com.zktravel.model.dto.coupon.CusCouponDTO;
import com.zktravel.model.po.CusCoupon;
import com.zktravel.model.vo.coupon.CouListVO;
import com.zktravel.model.vo.product.PlProductVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CusCouponServiceImpl implements CusCouponService {

    @Resource
    private CusCouponMapper cusCouponMapper;
    @Resource
    private TaProductMapper taProductMapper;

    //领取优惠券
    @Override
    public void receiveCoupon(CusCouponDTO dto, Long shopId, Long userId) {
        Long tpid = dto.getGoods_id();

        //获取该商品优惠金额（售价-柜面价）
        PlProductVO productVO = taProductMapper.selectProdByTpid(tpid, shopId);
        if (null == productVO) {
            throw new VisibleException(CodeEnum.PRODUCT_NOT_EXIST);
        }

        BigDecimal amt = productVO.getCounterPrice().subtract(productVO.getSellPrice());
        if (amt.compareTo(BigDecimal.ZERO) <= 0) {
            throw new VisibleException(CodeEnum.PRODUCT_NOT_COUPON);
        }

        //校验优惠券是否领取过
        CusCoupon tac = this.exist(tpid, shopId, userId);
        if (null != tac && tac.getAmt().compareTo(amt) >= 0) {
            throw new VisibleException(CodeEnum.COUPON_EXIST);
        }

        if (null != tac && tac.getAmt().compareTo(amt) < 0) {
            //更新优惠券的金额和过期时间
            this.updateCoupon(tac, amt);
            return;
        }

        saveCoupon(shopId, userId, amt, tpid);
    }

    //更新优惠券
    private void updateCoupon(CusCoupon existTac, BigDecimal newAmt) {
        Integer receiveTime = (int) (System.currentTimeMillis() / 1000);
        Date date = new Date();
        Integer expireTime = (int) (DatetimeUtils.addDate(date, CommonConstant.DAY_SEVEN).getTime() / 1000);
        CusCoupon copon = new CusCoupon();
        copon.setAmt(newAmt);
        copon.setLastAmt(existTac.getAmt());
        copon.setReceiveTime(receiveTime);
        copon.setExpireTime(expireTime);
        copon.setId(existTac.getId());
        copon.setUpdatedAt(date);

        cusCouponMapper.updateByPrimaryKeySelective(copon);
    }

    //保存优惠券
    private void saveCoupon(Long shopId, Long userId, BigDecimal amt, Long tpid) {
        Integer receiveTime = (int) (System.currentTimeMillis() / 1000);
        Date date = new Date();
        Integer expireTime = (int) (DatetimeUtils.addDate(date, CommonConstant.DAY_SEVEN).getTime() / 1000);
        CusCoupon copon = new CusCoupon();
        copon.setShopId(shopId);
        copon.setTpid(tpid);
        copon.setAmt(amt);
        copon.setOrgAmt(amt);
        copon.setStatus(CommonConstant.YES);
        copon.setReceiveTime(receiveTime);
        copon.setExpireTime(expireTime);
        copon.setUserId(userId);
        copon.setCreatedAt(date);
        cusCouponMapper.insertSelective(copon);
    }

    /**
     * @param tpidList
     * @param userId
     * @param shopId
     * @return 返回类型
     * @throws
     * @Title: getMapByTpids
     * @Description: 通过ta_product.id获取对应的优惠券
     * @author diaoxingguo
     * @date 2018年6月20日
     */
    @Override
    public Map<Long, CusCoupon> getMapByTpids(
            List<Long> tpidList, Long userId, Long shopId
    ) {
        //获取优惠券
        Map<Long, CusCoupon> couponMap = Maps.newHashMap();
        Integer expireTime = (int) (System.currentTimeMillis() / 1000);
        List<CusCoupon> cusCouponList = cusCouponMapper.listByTpids(tpidList, expireTime, userId, shopId);
        if (CollectionUtils.isNotEmpty(cusCouponList)) {
            for (CusCoupon cusCoupon : cusCouponList) {
                if (null == couponMap.get(cusCoupon.getTpid()) ||
                        couponMap.get(cusCoupon.getTpid()).getAmt().compareTo(cusCoupon.getAmt()) < 0) {
                    couponMap.put(cusCoupon.getTpid(), cusCoupon);
                }
            }

        }

        return couponMap;
    }

    /**
     * 查询优惠券列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<CouListResponse> getList(Long userId, Integer type, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Integer expireTime = null;
        Integer expired = null;
        Integer status = null;
        switch (type) {
            case 1:// 未使用
                status = 1; // 可用
                expireTime = (int) (System.currentTimeMillis() / 1000); // 过期时间大于这个值
                break;
            case 2:// 使用记录
                status = 0; // 已使用
                break;
            case 3:// 已过期
                status = 1; // 可用
                expired = (int) (System.currentTimeMillis() / 1000);
                break;
        }

        List<CouListVO> cusCouponList = this.cusCouponMapper.listByUserId(userId, expireTime, expired, status);
        List<CouListResponse> result = new ArrayList<>();
        for (CouListVO item : cusCouponList) {
            CouListResponse tmp = BeanUtils.copyProperties(item, CouListResponse.class);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            tmp.setExpireDate(sdf.format(new Date(item.getExpireTime() * 1000)));

            result.add(tmp);
        }
        return result;
    }
    
    
    //校验优惠券是否领取过
    @Override
    public CusCoupon exist(Long tpid, Long shopId, Long userId){
        Integer timeSec = (int) (System.currentTimeMillis() / 1000);
        CusCoupon cusCoupon = new CusCoupon();
        cusCoupon.setShopId(shopId);
        cusCoupon.setTpid(tpid);
        cusCoupon.setStatus(CommonConstant.YES);
        cusCoupon.setExpireTime(timeSec);
        cusCoupon.setUserId(userId);
        
        CusCoupon tac = cusCouponMapper.exist(cusCoupon);
		return tac;
    }
}
